package ldh.im.fxgui.controller;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import ldh.im.fxbase.util.MovableHelper;
import ldh.im.fxbase.util.StageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ResourceBundle;

public class StageControlController implements Initializable {

    private static Logger LOGGER = LoggerFactory.getLogger(StageControlController.class);

    @FXML private Button maxBtn;
    @FXML private Button remaxBtn;
    @FXML private Pane maxPane;
    @FXML private Pane root;

    private Stage newState = null;

    @FXML
    public void close(ActionEvent actionEvent) {
        if(StageUtil.isSupportTray() && getStage() == StageUtil.getMainStage()) {
            getStage().hide();
            getStage().setIconified(true);
        } else {
            LOGGER.debug("newStage close");
            EventHandler<WindowEvent> eventEventHandler =  getStage().getOnCloseRequest();
            getStage().close();
            if (eventEventHandler != null) {
                LOGGER.debug("newStage handle close event");
                eventEventHandler.handle(null);
            }
        }
    }

    @FXML private void min(ActionEvent actionEvent) {
        getStage().setIconified(true);
    }

    @FXML private void max(ActionEvent actionEvent) {
        getStage().setMaximized(true);
        maxBtn.setVisible(false);
        remaxBtn.setVisible(true);
    }

    @FXML private void remax(ActionEvent actionEvent) {
        getStage().setMaximized(false);
        maxBtn.setVisible(true);
        remaxBtn.setVisible(false);
    }

    public void hideMax() {
        maxPane.setVisible(false);
        maxPane.setManaged(false);
    }

    public void setStage(Stage stage) {
        this.newState = stage;
    }

    private Stage getStage() {
        if (newState == null) return StageUtil.getStage();
        return newState;
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        MovableHelper.movable(root);
    }
}
